-module(testFile).
-export([show/1, copy/2]).

show(Filename) ->
    case file:open(Filename, read) of
	{ok, IoDevice} -> showFile(IoDevice) ; 
	{error, Reason} -> {error, Reason}
    end.

showFile(IoDevice) ->
    case  file:read(IoDevice, 1) of
	{ok, Data} -> io:write(Data), showFile(IoDevice);
	eof -> file:close(IoDevice)
    end.

						% open(Filename, Modes) -> {ok, IoDevice} | {error, Reason}
						% read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason}
						% close(IoDevice) -> ok | {error, Reason}
						% write_file(Filename, Bytes) -> ok | {error, Reason}
						% write_file(Filename, Bytes, Modes) -> ok | {error, Reason}  

copy(Filename,CopyFilename) ->
    case {file:open(Filename, read), file:open(CopyFilename, write)} of
	{{ok, IoDeviceFrom},{ok,IoDeviceTo}} -> 
	    copyFile(IoDeviceFrom, IoDeviceTo) ; 
	{{error, Reason},_} -> 
	    {error, Reason};
	{_,{error, Reason}} -> 
	    {error, Reason}
    end.

copyFile(IoDeviceFrom, IoDeviceTo) ->
    case file:read(IoDeviceFrom, 1) of
	{ok, Data} -> 
	    case file:write(IoDeviceTo, Data) of
		ok -> 
		    copyFile(IoDeviceFrom, IoDeviceTo);
		{error, Reason} -> 
		    {error, Reason}
	    end;
	eof -> 
	    file:close(IoDeviceFrom),file:close(IoDeviceTo)
    end.


